package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.foolishbird.sdk.assist.CallbackObservable;
import com.foolishbird.sdk.assist.Constant;
import com.foolishbird.sdk.handler.SimpleAsyncResponseHandler;
import com.foolishbird.sdk.params.BindPhoneResponseParams;
import com.foolishbird.sdk.params.ResponseParams;
import com.foolishbird.sdk.params.bean.State;
import com.foolishbird.sdk.ui.view.DialogFactory;
import com.foolishbird.sdk.ui.view.ProgressDialog;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.ToolsUtils;
import com.foolishbird.sdk.utils.WL;


public class BaseHttpFragment extends Fragment {
    private static final String TAG = BaseHttpFragment.class.getSimpleName();
    private int screenHeight = ViewGroup.LayoutParams.MATCH_PARENT;
    private static final int REQUEST_PERMISSIONS = 0;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        if(context instanceof Activity){
            Display display = ((Activity)context).getWindowManager().getDefaultDisplay();
            screenHeight = Math.max(screenHeight, display.getHeight());
        }
    }



    protected final int getViewIdentifier(String name) {
        return ResUtils.getViewIdentifier(getContext(), name);
    }

    protected final int getLayoutIdentifier(String name) {
        return ResUtils.getLayoutIdentifier(getContext(), name);
    }

    protected final int getStringIdentifier(String name) {
        return ResUtils.getStringIdentifier(getContext(), name);
    }

    protected final int getDrawableIdentifier(String name) {
        return ResUtils.getDrawableIdentifier(getContext(), name);
    }

    protected final int getStyleIdentifier(String name) {
        return ResUtils.getStyleIdentifier(getContext(), name);
    }

    protected View doInflateContentView(LayoutInflater inflater, ViewGroup root, int resource) {
        if (inflater == null) {
            if (!isNullContext()) {
                inflater = LayoutInflater.from(getContext());
            } else {
                return null;
            }
        }
        return inflater.inflate(resource, root);
    }

    protected boolean isNullContext() {
        return getContext() == null;
    }

    /**
     * 获取应用程序名称
     */
    protected final String getAppName() {
        return ToolsUtils.getAppName(getContext());
    }

    protected Bundle getNotNullArguments(){
        Bundle bundle = getArguments();
        if(bundle == null){
            bundle = new Bundle();
        }
        return bundle;
    }

    @Override
    public void onStart() {
        super.onStart();
        this.isStoped = false;
        WL.d(TAG+this.getClass().getSimpleName(),"onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        this.isStoped = false;
        WL.d(TAG+this.getClass().getSimpleName(),"onResume");
    }
    private boolean isStoped = true;
    @Override
    public void onStop() {
        super.onStop();
        this.isStoped = true;
        WL.d(TAG+this.getClass().getSimpleName(),"onstop");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        WL.d(TAG+this.getClass().getSimpleName(),"onHiddenChanged"+hidden);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        WL.d(TAG,"onSaveInstanceState");
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        WL.d(TAG,"onViewStateRestored");
    }

    public final SimpleAsyncResponseHandler requestCallbackHandler(Class<? extends ResponseParams> paramsClass, Object... params) {
        return new AsyncCallbackHandler(paramsClass, params);
    }

    private class AsyncCallbackHandler<T extends ResponseParams> extends SimpleAsyncResponseHandler<T> implements Handler.Callback {

        private static final int MSG_SHOW_PROGRESSBAR = 0;
        private static final int MSG_DISMISS_PROGRESSBAR = 1;

        private final Handler mHandler;
        private final Object[] params;
        private final boolean autoLogin;
        private ProgressDialog dialog;

        public AsyncCallbackHandler(Class<T> responseParams, Object... params) {
            super(responseParams);
            this.params = params;
            this.autoLogin = params != null && params.length >= 3 && Boolean.parseBoolean((String) params[2]);
            dialog = DialogFactory.createProgressDialog(getContext());
            mHandler = new Handler(getActivity().getMainLooper(), this);
        }

        void sendShowProgressbarMessage() {
            mHandler.removeMessages(MSG_SHOW_PROGRESSBAR);
            mHandler.removeMessages(MSG_DISMISS_PROGRESSBAR);
            mHandler.sendEmptyMessageDelayed(MSG_SHOW_PROGRESSBAR, 500);
        }

        void sendDismissProgressbarMessage() {
            mHandler.removeMessages(MSG_SHOW_PROGRESSBAR);
            mHandler.removeMessages(MSG_DISMISS_PROGRESSBAR);
            mHandler.sendEmptyMessage(MSG_DISMISS_PROGRESSBAR);
        }

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SHOW_PROGRESSBAR:
                    if (dialog != null && !isStoped()) {
                        dialog.show();
                    }
                    break;
                case MSG_DISMISS_PROGRESSBAR:
                    if (dialog != null && !isStoped()) {
                        dialog.dismiss();
                        dialog = null;
                    }
                    break;

                default:
            }
            return true;
        }

        public void onAsyncCancel(int flag) {
            sendDismissProgressbarMessage();
            onAsyncRequestCancel(flag, params);
        }

        public void onAsyncSendRequest(int flag) {
//            sendShowProgressbarMessage();
            onAsyncRequestStart(flag, params);
        }

        public void onAsyncException(int flag, Exception ex) {
            sendDismissProgressbarMessage();
            onAsyncRequestException(flag, ex);
        }

        public void onAsyncNetworkException(int flag, Exception ex) {
            sendDismissProgressbarMessage();
            DialogFactory.createConfirmDialog(getContext(), getString(getStringIdentifier("hnssn_hint_network"))).show();
            onAsyncRequestNetworkException(flag, ex);
        }

        @Override
        public void onAsyncResponseSuccess(int flag, T response) {
            sendDismissProgressbarMessage();

            if (response != null && !isStoped() && !autoLogin) {
                if (State.SUCCESS != response.getState().getCode()&&0!=response.getState().getCode()) {
                    if(110 == response.getState().getCode()){
                        BindPhoneResponseParams message = (BindPhoneResponseParams)response;
                        DialogFactory.createIDFaildDialog(getContext(), message).show();
                    }else {
                        String message = response.getState().getMsg();
                        DialogFactory.createConfirmDialog(getContext(), message).show();
                    }


                }
            }

            onAsyncRequestResult(flag, response, params);
        }

    }

    public void onAsyncRequestCancel(int flag, Object... params) {
//        isSendHttpRequesting = false;
//        setSubmitButtonEnabled(true);
        WL.d(TAG, "onAsyncReuqestCancel ---> flag: " + flag);
    }

    public void onAsyncRequestStart(int flag, Object... params) {
//        isSendHttpRequesting = true;
//        setSubmitButtonEnabled(false);
        WL.d(TAG, "onAsyncReuqestStart ---> flag: " + flag);
    }

    public void onAsyncRequestNetworkException(int flag, Exception ex) {
//        isSendHttpRequesting = false;
//        setSubmitButtonEnabled(true);
        WL.d(TAG, "onAsyncReuqestNetworkException ---> flag: " + flag);
        CallbackObservable.getInstance().callExcetion(Constant.CallType.CALL_LOGIN, ex);
    }

    public void onAsyncRequestException(int flag, Exception ex) {
//        isSendHttpRequesting = false;
//        setSubmitButtonEnabled(true);
        WL.d(TAG, "onAsyncReuqestException ---> flag: " + flag);
        CallbackObservable.getInstance().callExcetion(Constant.CallType.CALL_LOGIN, ex);
    }

    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
//        isSendHttpRequesting = false;
//        setSubmitButtonEnabled(true);
        WL.d(TAG, "onAsyncReuqestResult ---> flag: " + flag);
    }

    protected boolean isStoped() {
        return this.isStoped;
    }
}
